package com.example.md.mddemo.tabledemo.tableroute;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Copyright © 2018年 ziniuxiaozhu. All rights reserved.
 *
 * @Author 临江仙 hzqiuxm@163.com
 * 使用AOP拦截特定的注解去添加表后缀
 * @Date 2018/9/5 15:07
 */

@Slf4j
@Aspect
@Component
public class HandlerTable {

    @Pointcut("@annotation(com.example.md.mddemo.tabledemo.tableroute.Router)||@within(com.example.md.mddemo.tabledemo.tableroute.Router)")
    public void aopPoint() {
    }


    @Before("aopPoint()")
    public void doBefore(JoinPoint joinPoint) throws Exception {

        Method method = getMethod(joinPoint);
        Router router = method.getAnnotation(Router.class);
        //获取路由字段
        String companyCode = router.companyCode();
        log.info("-------------- companyCode = {}",companyCode);
        //加入分表后綴，實際情況由參數传入
        DbContextHolder.setTableIndex(companyCode);
        System.out.println(DbContextHolder.getTableIndex());
        Object[] args = joinPoint.getArgs();

        System.out.println(args);
//        if (args != null && args.length > 0){
//            for (int i = 0; i < args.length; i++){
//                String routeFieldValue = BeanUtils.getProperty(args[i],companyCode);
//                log.info("-------------- routeFieldValue = {}",routeFieldValue);
//
//                if(routeFieldValue != null&&routeFieldValue!=""){
//                    DbContextHolder.setTableIndex(routeFieldValue);
//                }
//            }
//        }
    }


    private Method getMethod(JoinPoint jp) throws NoSuchMethodException {
        Signature sig = jp.getSignature();
        MethodSignature msig = (MethodSignature) sig;

//        System.out.println("sig = "+ sig);
//        System.out.println("sig.getName()"+sig.getName());
//        System.out.println("msig = "+ msig);
//        System.out.println("msig.getName() = "+ msig.getName());
//        System.out.println("getClass(jp) = "+ getClass(jp));
        return getClass(jp).getMethod(msig.getName(), msig.getParameterTypes());
    }

    private Class<? extends Object> getClass(JoinPoint jp)
            throws NoSuchMethodException {
        return jp.getTarget().getClass();
    }




}
